package com.freud.logic.business.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.freud.framework.base.BaseController;
import com.freud.framework.base.BaseRequest;
import com.freud.logic.business.bean.Repository;
import com.freud.logic.business.service.DistrictService;
import com.freud.logic.business.service.RepositoryService;

@Controller
@RequestMapping("/repository")
public class RepositoryController extends BaseController {

	@Autowired
	private DistrictService districtService;

	@Autowired
	private RepositoryService repositoryService;

	@RequestMapping(value = "/index")
	public ModelAndView index() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("repository.index");
		return mav;
	}

	@RequestMapping(value = "/list")
	@ResponseBody
	public Map<String, Object> list(BaseRequest baseRequest) {

		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", repositoryService.getAll(buildRowBounds()).size());
		result.put("rows",
				repositoryService.getAll(buildRowBounds(baseRequest)));
		return result;
	}

	@RequestMapping(value = "/add")
	public ModelAndView add() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("repository.add");
		mav.addObject("districts", districtService.getAll());
		return mav;
	}

	@RequestMapping(value = "/save")
	public String save(Repository repository) {
		repositoryService.insert(repository);
		return "redirect:/repository/index";
	}

	@RequestMapping(value = "/edit")
	public ModelAndView edit(Integer id) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("repository.edit");
		mav.addObject("repository", repositoryService.getById(id));
		mav.addObject("districts", districtService.getAll());
		return mav;
	}

	@RequestMapping(value = "/update")
	public String update(Repository repository) {
		repositoryService.update(repository);
		return "redirect:/repository/index";
	}

	@RequestMapping(value = "/map")
	public ModelAndView map(Integer id) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("repository.map");
		mav.addObject("repository", repositoryService.getById(id));
		return mav;
	}

	@RequestMapping(value = "/delete")
	public String deleter(Integer id) {
		repositoryService.delete(id);
		return "redirect:/repository/index";
	}
}
